<template>
  <div class="person-info">
    <el-card class="info-card">
      <template #header>
        <div class="card-header">
          <span>个人信息</span>
        </div>
      </template>
      
      <div class="info-content">
        <el-form 
          :model="userInfo" 
          :rules="infoRules" 
          ref="userInfoFormRef" 
          label-width="100px"
        >
          <el-form-item label="用户ID" prop="id">
            <el-input v-model="userInfo.id" disabled></el-input>
          </el-form-item>
          <el-form-item label="用户名" prop="username">
            <el-input v-model="userInfo.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="姓名" prop="name">
            <el-input v-model="userInfo.name"></el-input>
          </el-form-item>
          <el-form-item label="角色" prop="role">
            <el-input v-model="userInfo.role" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="userInfo.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="phone">
            <el-input v-model="userInfo.phone"></el-input>
          </el-form-item>
          <el-form-item label="创建时间" prop="createTime">
            <el-input v-model="userInfo.createTime" disabled></el-input>
          </el-form-item>
          <el-form-item>
            <el-button 
              type="primary" 
              @click="saveInfo" 
              :loading="loading"
            >
              保存修改
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    
    <el-card class="avatar-card" style="margin-top: 20px;">
      <template #header>
        <div class="card-header">
          <span>头像设置</span>
        </div>
      </template>
      
      <div class="avatar-content">
        <el-upload
          class="avatar-uploader"
          action="/api/upload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          :disabled="uploading"
          :headers="uploadHeaders"
        >
          <img v-if="userInfo.avatar" :src="userInfo.avatar" class="avatar">
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          <template #tip v-if="uploading">
            <div class="el-upload__tip">正在上传...</div>
          </template>
        </el-upload>
        <div class="avatar-tips">点击上传新头像，建议尺寸 200x200 像素</div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import request from '@/utils/request'
import router from '@/router/index.js'

// 初始化测试token
localStorage.setItem('token', 'test-token-123')

const userInfoFormRef = ref(null)
const loading = ref(false)
const uploading = ref(false)

const userInfo = ref({
  id: '',
  username: '',
  name: '',
  role: '',
  email: '',
  phone: '',
  avatar: '',
  createTime: ''
})

const uploadHeaders = {
  Authorization: `Bearer ${localStorage.getItem('token')}`
}

const infoRules = reactive({
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 50, message: '姓名长度应在 2 到 50 个字符之间', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入有效的邮箱地址', trigger: ['blur', 'change'] }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号', trigger: ['blur', 'change'] }
  ]
})

const fetchUserInfo = async () => {
  try {
    const res = await request.get('/api/user/info', {
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    })
    if (res.status === 'success') {
      userInfo.value = { ...res.data }
    } else {
      throw new Error(res.message || '获取用户信息失败')
    }
  } catch (error) {
    console.error('获取用户信息错误:', error)
    ElMessage.error(error.response?.data?.message || '获取用户信息失败')
    
    if (error.response?.status === 401) {
      localStorage.removeItem('token')
      ElMessage.info('登录已过期，请重新登录')
      await router.push('/login')
    }
  }
}

const saveInfo = async () => {
  try {
    loading.value = true
    await userInfoFormRef.value.validate(async (valid) => {
      if (valid) {
        const { id, username, role, createTime, ...updateData } = userInfo.value
        await request.put('/api/user/info', updateData, {
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('token')}`
          }
        })
        ElMessage.success('个人信息更新成功')
        await fetchUserInfo()
      }
    })
  } catch (error) {
    ElMessage.error(error.response?.data?.message || '保存失败')
  } finally {
    loading.value = false
  }
}

const handleAvatarSuccess = async (res) => {
  try {
    if (res.status === 'success' && res.data?.url) {
      userInfo.value.avatar = res.data.url
      await request.put('/api/user/info', { avatar: userInfo.value.avatar }, {
        headers: {
          'Authorization': `Bearer ${localStorage.getItem('token')}`
        }
      })
      ElMessage.success('头像更新成功')
    } else {
      ElMessage.error(res.message || '头像上传失败')
    }
  } catch (error) {
    console.error('更新头像错误:', error)
    ElMessage.error(error.response?.data?.message || '头像更新失败')
    
    if (error.response?.status === 401) {
      localStorage.removeItem('token')
      ElMessage.info('登录已过期，请重新登录')
      await router.push('/login')
    }
  } finally {
    uploading.value = false
  }
}

const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isJPG) {
    ElMessage.error('头像图片只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('头像图片大小不能超过 2MB!')
    return false
  }
  
  uploading.value = true
  return isJPG && isLt2M
}

onMounted(() => {
  fetchUserInfo()
})
</script>

<style scoped>
.person-info {
  padding: 20px;
}

.card-header {
  font-size: 18px;
  font-weight: bold;
}

.info-content {
  max-width: 600px;
}

.avatar-content {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.avatar-uploader {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 150px;
  height: 150px;
  margin-bottom: 15px;
}

.avatar-uploader:hover {
  border-color: var(--el-color-primary);
}

.avatar {
  width: 100%;
  height: 100%;
  display: block;
  object-fit: cover;
}

.avatar-tips {
  color: var(--el-text-color-secondary);
  font-size: 14px;
}

.el-upload__tip {
  margin-top: 8px;
  color: var(--el-text-color-secondary);
}
</style>